<template>
  <!-- AddAuthor 组件 -->
  <!--  <AddAuthor  @author-added="handleAuthorAdded" />-->
  <el-button type="primary" @click="handleAddData">添加数据</el-button>
  <!--添加一个用于筛选的数据框-->
  <el-form :inline="true" :model="filterForm">
    <el-form-item label="查询时间段">
      <el-date-picker
          v-model="filterForm.start_date"
          type="datetime"
          placeholder="选择开始日期"

      />
      <el-date-picker
          v-model="filterForm.end_date"
          type="datetime"
          placeholder="选择结束日期"

      />
      <el-button type="primary" @click="handleFilter">刷新</el-button>
    </el-form-item>

  </el-form>
  <el-table :data="tableData.value" border type="index" style="width: 100%" v-loading="table_loading">
    <el-table-column
        v-for="(value, key) in get_reportInfo"
        :key="key"
        :prop="key"
        :label="value.verbose_name"
        :width="120"
    ></el-table-column>
    <!-- 附件列保持不变，但假设添加了一个attachmentText字段用于显示附件名 -->
    <el-table-column prop="attachment" label="附件" width="120">
      <template #default="scope">
        <a :href="scope.row.attachment" target="_blank">{{ scope.row.attachmentText || '附件' }}</a>
        <el-button size="small" type="primary" @click="handleFileUpload(scope.row)">点击上传</el-button>
        <input
            type="file"
            style="display: none;"
            ref="fileInput"
            @change="onFileSelected($event)"
        />
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="180"> <!-- "Operations"改为中文"操作" -->
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClickDelete(scope.row)">删除</el-button>
        <el-button link type="primary" size="small" @click="handleClickEdit(scope.row)">编辑</el-button>
        <el-button link type="primary" size="small" @click="handleClickDownlaodWord(scope.row)">导出word</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-container">
  <el-pagination
        v-model:currentPage="filterForm.page"
        :page-size="10"
        layout="prev, pager, next"
        :total="total_datas "
        @current-change="handleCurrentChange"
    />
    </div>
  <AddData  :isAdmin="false" @refresh-table="handleSucceedAdd"  />
  <EditData :isAdmin="false" @refresh-table="handleSucceedEdit" />
</template>

<script setup>
import {ref, onMounted, watchEffect, onBeforeUnmount, reactive} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage, ElMessageBox} from "element-plus";

import global, {formDataApi, jsonApi} from "@/global.js";
import AddData from "@/components/Main/CourseAdjustmentManagement/AddData.vue";
import EditData from "@/components/Main/CourseAdjustmentManagement/EditData.vue";

const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});
const filterForm = reactive({
  start_date: '',
  end_date: '',
  page: 1,
});
// State
const reportInfo = ref({});
const get_reportInfo = ref({});
const tableData = reactive([]);
let orgTableData = null;//原始数据，其中的json没有经过json.parse
const fileInput = ref(null);
let currentRow = ref(null);
const table_loading = ref(false);
let total_datas = ref(0);
onMounted(() => {
  //开启接收事件监听
  // 获取当前日期
// 设置结束日期为今天
  const now = new Date();
// 获取本地时区的年、月、日、时、分、秒
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并且补零
  const date = String(now.getDate()+1).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  // 拼接成 "yyyy-MM-dd HH:mm:ss" 格式
  filterForm.end_date = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
  // 判断当前日期属于哪个学期，并设置起始日期
   let start_date;
   if (now.getMonth() >= 7) { // 当前时间是8月到12月之间，开学时间应为8月1日
       start_date = new Date(now.getFullYear(), 7, 1); // 设置时间为8月1日
   } else if (now.getMonth() < 2) { // 当前时间是1月到1月，开学时间应为去年8月1日
       start_date = new Date(now.getFullYear() - 1, 7, 1); // 设置时间为去年8月1日
   } else { // 当前时间是2月到7月之间，开学时间应为2月1日
       start_date = new Date(now.getFullYear(), 1, 1); // 设置时间为2月1日
   }
      // 手动格式化日期为 "YYYY-MM-DD" 格式
   function formatDate(date) {
     const year = date.getFullYear();
     const month = String(date.getMonth() + 1).padStart(2, '0');
     const day = String(date.getDate()).padStart(2, '0');
     return `${year}-${month}-${day}`;
   }

   // 设置filterForm.start_date为计算出的学期开始日期
   filterForm.start_date = formatDate(start_date);
});

onBeforeUnmount(() => {
  //关闭事件监听

});

// Methods
const handleAddData = () => {
  eventBus.emit('course-adjustment-form-table-add', {})
};
const handleSucceedAdd = () => {
  ElMessage({
    message: '添加成功',
    type: 'success',
  });
  // 设置结束日期为今天
  const now = new Date();
// 获取本地时区的年、月、日、时、分、秒
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并且补零
  const date = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  // 拼接成 "yyyy-MM-dd HH:mm:ss" 格式
  filterForm.end_date = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
  refreshTable();
};
const handleSucceedEdit = () => {
  ElMessage({
    message: '编辑成功',
    type: 'success',
  });
  refreshTable();
};
const handleFilter = () => {
  // 获取筛选条件
  getDataWithAccessToken(props.tableType);


};
const handleCurrentChange = (currentPage) => {
  // 更新当前页码
  filterForm.page = currentPage;
  // 重新加载数据
  getDataWithAccessToken(props.tableType);
};
const getDataWithAccessToken = async () => {
  const requestBody = {
    start_time: filterForm.start_date,
    end_time: filterForm.end_date,
    page: filterForm.page,
  };

  try {
    table_loading.value = true;
    const response = await jsonApi('/courseadjustmentmanagement/get/',JSON.stringify(requestBody));
    let orgdata = await response.json();
    const data = orgdata['datas'];
    total_datas = orgdata['total_datas'];
    orgTableData = JSON.parse(JSON.stringify(data));
    if (!response.ok) {
      showError('获取数据失败', data.error, 2000);
    } else {
      tableData.value = data; // 假设返回的数据直接用于表格

    }
    table_loading.value = false;
  } catch (error) {
    console.error(error);
    table_loading.value = false;
  }
};
const getCourseadJustmentInfo = async () => {
  //获取字段
  if(!localStorage.getItem('CourseadJustmentInfo')) {
    const response = await jsonApi('/courseadjustmentmanagement/getmodelfields/',"");
    const data = await response.json();
    if (response.ok) {
      localStorage.setItem('CourseadJustmentInfo', JSON.stringify(data));
      await getCourseadJustmentInfo();
    } else {
         ElMessage(
             {
               message: '获取数据失败',
               type: 'error',
               duration: 2000,
             }
         );
    }
  }
  //将字符串转为对象
  reportInfo.value = JSON.parse(localStorage.getItem('CourseadJustmentInfo'));
  get_reportInfo.value =reportInfo.value['TeacherChangeClassRecord']
  const get_excludeFields = ['model_name', 'attachment'];
  // 使用 forEach 循环来遍历对象的所有键
  get_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (get_reportInfo.value.hasOwnProperty(field)) {
      delete get_reportInfo.value[field];
    }
  });
}



//删除表格数据
const handleClickDelete = async (row) => {

  try {
    const requestBody = {"id": row.id, "Report": props.tableType};
    const response = await jsonApi('/courseadjustmentmanagement/delete/',JSON.stringify(requestBody));
    const data = await response.json();

    if (data.code === 'token_not_valid') {
      if (await global.refreshAndRetry()) {
        //成功刷新重新执行
        await self.handleClickDelete();
      }
    } else if (!response.ok) {
      ElMessage({
        type: 'error',
        message: data.error || '删除失败'
      });
    } else {
      await refreshTable();
      ElMessage({
        type: 'success',
        message: '删除成功!'
      });
    }
  } catch (error) {
    console.error('删除过程中发生错误:', error);
    ElMessage({
      type: 'error',
      message: '网络错误，请重试'
    });
  }
}
//修改表格数据相关
const handleClickEdit = async (row) => {
  let data;
  // 返回orgTableData中的id==row.id的数据
  data = orgTableData.find(item => item.id === row.id);
  //修改当前表格行的数据，将会弹出一个上文的<el-dialog>，这个表单具有当前行的数据
  eventBus.emit('course-adjustment-form-table-edit', {
    editData: data,
    ID: row.id,
  })
}
//下载word
const handleClickDownlaodWord = async (row) => {
  ElMessage({
    message: 'word导出后需调整格式后打印',
    type: 'info',
    duration: 2000
  })
  try {
    const response = await jsonApi('/courseadjustmentmanagement/downloadword/', JSON.stringify({"id": row.id}));

    if (response.ok) {
      // 创建一个blob对象，它表示了一段不可变的原始数据
      const blob = await response.blob();

      // 创建一个链接元素，用于下载文件
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;

      // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
      let fileName = 'downloaded.docx'; // 默认文件名
      const contentDisposition = response.headers.get('content-disposition');
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
        if (fileNameMatch) {
          fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
        }
      }

      a.download = fileName;

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }else{
      const data = await response.json();
      ElMessage({
        message: '下载失败: '+data.error,
        type:  'error',

      })
    }
  } catch (e) {
    ElMessage({
      message: '下载失败: '+e,
      type: 'error'

    })
  }
};

// 上传相关
const handleFileUpload = async (row) => {
  // 触发隐藏的 file input 的点击事件，以打开文件选择对话框
  fileInput.value.click();
  // 你可能需要在这里以某种方式将当前行数据传递给文件上传处理函数
  // 例如，可以将 row 保存在一个组件的数据属性中，以便稍后在文件选择后使用
  currentRow = row;
};
const onFileSelected = async (event) => {
  const file = event.target.files[0];
  if (file) {
    //检查file是不是pdf或者zip
    if (file.type === 'application/pdf' || file.type === 'application/x-zip-compressed') {
      // 显示上传进度
      // 在这里处理文件上传逻辑
      await uploadFile(currentRow, file);
    } else {
      // 显示错误消息
      ElMessage.error('请选择PDF或ZIP文件');
    }


  }
};
const uploadFile = async (row, file) => {
  // 创建 FormData 对象，并添加文件和其他可能需要的数据
  const formData = new FormData();
  const accessToken = localStorage.getItem('access_token');
  formData.append('file', file);
  formData.append('id', row.id); // 假设每一行数据有一个唯一的 id
  formData.append('Report', props.tableType); // 假设每一行数据有一个唯一的 id
  // 使用 Axios、Fetch API 或 XMLHttpRequest 发送文件到服务器
  try {
    // const response = await fetch(setting.API_URL + '/reportmanager/upload/', {
    //   method: 'POST',
    //   body: formData,
    //   headers: {
    //     'Authorization': `Bearer ${accessToken}`,
    //   },
    // });
    const response = await formDataApi('/courseadjustmentmanagement/upload/', formData)
    const data = await response.json();
    console.log(data);
    if (!response.ok) {
        ElMessage({
          type: 'error',
          message: data.error
        });


      throw new Error(`HTTP error! data: ${data}`);

    } else {
      ElMessage({
        type: 'success',
        message: '上传成功!'
      });
      await refreshTable();
      console.log('File uploaded successfully', data);

    }


  } catch (error) {
    console.error('文件上传失败', error);
  }
};


//刷新表格获取新数据
const refreshTable = async () => {
  // 获取新的数据
  await getDataWithAccessToken();
};


watchEffect(async () => {
    await getCourseadJustmentInfo();
    await getDataWithAccessToken();
});


function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}
</script>

<style>
/* 添加样式 */
</style>
